<template>
  <div>
    <el-card calss="box-card">
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
      <!-- 表格组件 -->
      <!-- table
        --boeder:可以设置表格纵向是否有边框
        --table—colum
        --label：某一个列表
        --width：设置这列宽度
        --align：设置这一列对齐方式
    -->
      <el-table border style="margin:10px 0 ;" :data="trademarkArr">
        <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
        <el-table-column label="品牌名称" prop="tmName">
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" alt="" style="width: 100px;height: 100px;">
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)"></el-button>

            <el-popconfirm :title="`您确定要删除${row.tmName}?`" width="250px" icon="Delete"
              @confirm='removeTradeMark(row.id)'>
              <template #reference>
                <el-button type="primary" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <!-- v-model:current-page=""当前页数
        v-model:page-size设置每页展示多少条数据
        page-sizes	每页显示个数选择器的选项设置
            :background="background"是否为分页按钮添加背景色
    -->
      <el-pagination @size-change="changeLimit" @current-change="getHasTrademark" :pager-count="9"
        v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]" :background=true
        layout=" prev, pager, next, jumper,->, sizes,total" :total=total />

    </el-card>
    <!-- 对话框组件：在添加品牌与修改已有品牌的业务时候使用 -->
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'" width="500">
      <el-form style="width: 80%;" :model="trademarkParams" :rules="rules">
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="80px" prop="logUrl">
          <!--  upload组件属性：action图片上传路径没写api，代理服务器不发送这次post请求-->
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="true"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽：footer -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { reqHasTrademark, reqAddOrUpdatetrademark, reqDeleteTrademark } from '@/api/product/trademark';
import type { Records, TradeMarkResponseData, TradeMark } from '@/api/product/trademark/type';
import { ElMessage, type UploadProps } from 'element-plus';
// 当前页码
let pageNo = ref<number>(1);
// 每一页展示多少条数据
let limit = ref<number>(3);
// 存储已有品牌数据总数
let total = ref<number>(0);
// 存储已有品牌数据
let trademarkArr = ref<Records>([]);
//控制对话框的显示与隐藏 true显示
let dialogFormVisible = ref<boolean>(false);
// 定义一个收集新增品牌的数组
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})
// 获取已有品牌的接口分装成一个函数：在任何情况下获取数据，调用该函数即可
const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager;
  let result: TradeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value);
  if (result.code == 200) {
    // 存储已有品牌总个数
    total.value = result.data.total;
    trademarkArr.value = result.data.records;
    console.log(trademarkArr.value);


  }
};
//气泡框确认按钮的回调-》删除已有品牌
const removeTradeMark = async (id: number) => {
  let result:any = await reqDeleteTrademark(id);
  if (result.code == 200) {
    //删除成功的提示信息
    ElMessage({
      type: 'success',
      message: '删除品牌成功！'
    })
    //再次获取品牌信息
    getHasTrademark(trademarkArr.value.length>1?pageNo.value:pageNo.value-1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败！'
    })
  }
}

// 组件一挂载发送请求获取品牌                                 
onMounted(() => {
  getHasTrademark();
});
// 分页器当前页码发生变化的时候会触发
// const changePageNo = () => {
//   getHasTrademark();
// }
// 当下拉菜单发生变化时会触发
const changeLimit = () => {
  // pageNo.value=1;
  getHasTrademark()
}
// 添加品牌按钮的回调
const addTrademark = () => {
  dialogFormVisible.value = true;
  // 清空收集的数据
  trademarkParams.id = 0;
  trademarkParams.logoUrl = '',
    trademarkParams.tmName = ''
}
// 修改品牌按钮的回调
const updateTrademark = (row: TradeMark) => {
  console.log(row);
  dialogFormVisible.value = true;
  // es6合并对象
  Object.assign(trademarkParams, row);
  // // 获取id
  // trademarkParams.id=row.id;
  // // 展示已有品牌的数据
  // trademarkParams.tmName=row.tmName;
  // trademarkParams.logoUrl=row.logoUrl;
}
//对话框底部取消按钮 
const cancel = () => {
  dialogFormVisible.value = false;
}
// 对话框底部确定按钮
const confirm = async () => {
  let result: any = await reqAddOrUpdatetrademark(trademarkParams);
  if (result.code == 200) {
    // 关闭对话框
    dialogFormVisible.value = false;
    // 弹出提示信息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    // 再次发请求获取全部品牌信息
    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
    // 收集情况

  } else {
    // 添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    dialogFormVisible.value = false;
  }

  console.log(result);

}
// 上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile);
  //  钩子是在图片上传前触发的，上传文件之前可以约束文件类型与大小
  //  要求:上传文件格式png|jpg|gif 4M
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M'
      })
      return false;
    }
  } else {
    ElMessage({
      type: 'error',
      message: '文件上传格式必须是PNG|JPG|GIF',
    })
    return false;
  }
}
// 图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  trademarkParams.logoUrl = response.data;
}
// 表单校验规则对象
const rules = {
  tmName: [

  ],
  logoUrl: []
}
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>